import axios from "axios";
import { showNotify, Loading } from "vant";
// import store from "@/stores";
import { getToken, removeToken } from "@/utils/auth";
import { redirect, blobValidate } from "@/utils/index";
let downloadLoadingInstance;
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL, // url = base url + request url
  timeout: 50000
});

// request interceptor
service.interceptors.request.use(
  config => {
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false;
    if (getToken() && !isToken) {
      config.headers["Authorization"] = "Bearer " + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    // config.headers["APP_TYPE"] = import.meta.env.VITE_SUB_APP_CODE;
    // if (store.state.token) {
    //   config.headers["Authorization"] = "Bearer " + getToken();
    // }
    return config;
  },
  error => {
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    const res = response.data;
    res.headers = response.headers;
    if (res.code && res.code != 200) {
      //返回码错误,错误提示这里已经统一处理，单个请求可以不再弹出消息
      const { hideMessageCodes } = response.config.headers;
      if (!hideMessageCodes || !hideMessageCodes.includes(res.code)) {
        //如果头部不含hideMessageCodes，则直接调用后端的message提示，否则，接口调用的时候自行判断处理
        showNotify({ type: "warning", message: res.msg || "网络请求异常" });
      }
      return Promise.resolve(res || "Error"); // 错误结果返回
      //return new Error(res || 'Error')  //之前是为了处理message不需要取后端返回的情况，现在用hideMessageCodes处理
    } else {
      // if (res.code == "450") {
      //   removeToken();
      //   // store.state.userInfo = null;
      //   redirect();
      // }
      return res;
    }
  },
  error => {
    console.log("error", error);
    const { code, msg } = error.response.data;
    showNotify({ type: "warning", message: msg || "网络请求异常" });
    // if (code == "450") {
    //   removeToken();
    //   // store.state.userInfo = null;
    //   redirect();
    // }
    return Promise.reject(error);
  }
);
// 通用下载方法
export function download(url, params, filename, config) {
  downloadLoadingInstance = Loading.service({
    text: "正在下载数据，请稍候",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)"
  });
  return service
    .post(url, params, {
      // headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: "blob",
      ...config
    })
    .then(async data => {
      const isLogin = await blobValidate(data);
      if (isLogin) {
        const blob = new Blob([data]);
      } else {
        showNotify({ type: "error", message: data.msg || "网络请求异常" });
      }
      downloadLoadingInstance.close();
    })
    .catch(err => {
      showNotify({ type: "error", message: err || "网络请求异常" });
      downloadLoadingInstance.close();
    });
}
export default service;
